// 存储

declare type StorageType = 'local' | 'session';

class Storage {
  private readonly prefix?: string = 'default_';
  private readonly type?: StorageType = 'local';

  constructor(type?: StorageType, prefix?: string) {
    this.type = type || 'local';
    this.prefix = prefix || 'default_';
  }

  private wrapper(key: string) {
    return `${ this.prefix }${ key }`;
  }

  public set(key: string, value: any): void {
    if (this.type === 'local') {
      localStorage.setItem(this.wrapper(key), value);
    } else if (this.type === 'session') {
      sessionStorage.setItem(this.wrapper(key), value);
    } else {
      // Not Support
    }
  }

  public get(key: string): any {
    if (this.type === 'local') {
      return localStorage.getItem(this.wrapper(key));
    } else if (this.type === 'session') {
      return sessionStorage.getItem(this.wrapper(key));
    } else {
      return null;
    }
  }

  public remove(key: string): void {
    if (this.type === 'local') {
      localStorage.removeItem(this.wrapper(key));
    } else if (this.type === 'session') {
      sessionStorage.removeItem(this.wrapper(key));
    } else {
      // Not Support
    }
  }

  public clear() {
    if (this.type === 'local') {
      const keys = Object.keys(localStorage);
      if (keys && Array.isArray(keys)) {
        keys.forEach(key => {
          if (key.indexOf(`${ this.prefix }`) === 0) {
            localStorage.removeItem(key);
          }
        });
      }
    } else if (this.type === 'session') {
      const keys = Object.keys(sessionStorage);
      if (keys && Array.isArray(keys)) {
        keys.forEach(key => {
          if (key.indexOf(`${ this.prefix }`) === 0) {
            sessionStorage.removeItem(key);
          }
        });
      }
    } else {
      // Not Support
    }
  }
}

const storage = new Storage();

export {
  Storage, storage,
};
